package cn.faster.config.filter;

import cn.faster.sys.config.SpringFrameworkConfig;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaoCoder
 * @version 1.0
 * @description: TODO token校验
 * @date 2021/8/11 21:13
 */
@Log4j2
@Component
public class TokenInterceptor implements HandlerInterceptor {

    //@Autowired
    private SpringFrameworkConfig springFrameworkConfig;

    //@Autowired
    private StringRedisTemplate redisTemplate;

    //@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //if (Boolean.getBoolean(springFrameworkConfig.getIgnoreToken())){
        //    log.info(">>>TokenInterceptor preHandle 开始拦截>>> {}", request.getRequestURI());
        //    String token = request.getHeader("token");
        //    log.info(">>>head>>>token:{}", token);
        //    //SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        //    SysUser sysUser = ShiroSecurityUtils.getLoginSysUserInfo();
        //    // 获取缓存中的 token 值
        //    String s;
        //    if (token == null || token.equals("") || sysUser == null) {
        //        log.error(">>>token为空>>>调用>>>{}接口>>>失败>>>", request.getRequestURI());
        //        return false;
        //    } else {
        //        s = redisTemplate.getCacheObject(sysUser.getUsername() + sysUser.getId());
        //        log.info("redis中token:{}", s);
        //    }
        //    // 检验token是否正确
        //    if (s == null) {
        //        log.error(">>>还未登录>>>失败>>>");
        //        return false;
        //    }
        //    if (!s.equals(token)) {
        //        log.error(">>>token有误>>>{}>>>失败>>>", request.getRequestURI());
        //        return false;
        //    }
        //    log.info(">>>token续命>>>");
        //    // 续命 redis 中的token
        //    redisTemplate.setCacheObject(sysUser.getUsername() + sysUser.getId(),token,10, TimeUnit.MINUTES);
        //    log.info(">>>token正确>>>{}>>>成功>>>", request.getRequestURI());
        //}

        return true;

    }

    //@Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //@Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
